package com.aitangbao.web.utils;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.aitangbao.core.model.KJob;
import com.aitangbao.core.model.KJobTrans;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
public class CommonUtils {

    /**
     * @param uId     用户ID
     * @param jobFile 上传的作业文件
     * @return String
     * @throws IOException
     * @Title saveFile
     * @Description 保存上传的作业文件
     */
    public static String saveFile(Integer uId, String kettleFileRepository, MultipartFile jobFile) throws IOException {
        StringBuilder allLogFilePath = new StringBuilder();
        allLogFilePath.append(kettleFileRepository).append("/")
                .append(uId).append("/")
                .append(System.currentTimeMillis()).append("/")
                .append(jobFile.getOriginalFilename());
        FileUtils.writeByteArrayToFile(new File(allLogFilePath.toString()), jobFile.getBytes());
        return allLogFilePath.toString();
    }

    /**
     * @param startTime  起始时间
     * @param stopTime   结束时间
     * @param resultList 递归的返回值
     * @return List<Integer>
     * @Title getEveryDayData
     * @Description 确定每一次运行属于哪一天
     */
    public static List<Integer> getEveryDayData(Long startTime, Long stopTime, List<Integer> resultList) {
        List<Long> timeList = new ArrayList<Long>();
        try {
            for (int i = -6; i <= 1; i++) {
                Calendar instance = Calendar.getInstance();
                instance.add(Calendar.DATE, i);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateFormat = simpleDateFormat.format(instance.getTime());
                Long time = simpleDateFormat.parse(dateFormat).getTime();
                timeList.add(time);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Integer startDay = 0;
        Integer stopDay = 0;
        for (int i = 0; i <= 6; i++) {
            if (timeList.get(i) < startTime && startTime < timeList.get(i + 1)) {
                startDay = i;
            }
            if (timeList.get(i) < stopTime && stopTime < timeList.get(i + 1)) {
                stopDay = i;
            }
        }
        if ((stopDay - startDay) > 0) {
            for (int i = startDay; i <= stopDay; i++) {
                resultList.set(i, resultList.get(i) + 1);
            }
        } else {
            resultList.set(startDay, resultList.get(startDay) + 1);
        }
        return resultList;
    }

    /**
     * 保存job与tran文件
     *
     * @param getuId
     * @param kettleFileRepository
     * @param jobFile
     * @param transFiles
     * @throws IOException
     */
    public static KJobTrans saveJobFileAndTransFile(Integer getuId, String kettleFileRepository, MultipartFile jobFile, MultipartFile[] transFiles) throws IOException {
        //定义返回
        KJobTrans kJobTrans = new KJobTrans();
        List<String> transName = new ArrayList<>();
        //保存路径
        StringBuilder allLogFilePath = new StringBuilder();
        allLogFilePath.append(kettleFileRepository).append("/")
                .append(getuId).append("/")
                .append(System.currentTimeMillis()).append("/");
        //job全路径
        String jobPath = allLogFilePath.toString() + jobFile.getOriginalFilename();
        FileUtils.writeByteArrayToFile(new File(jobPath), jobFile.getBytes());
        kJobTrans.setJobPath(jobPath);
        //遍历保存转换
        for (MultipartFile tranFile : transFiles) {
            String tranPath = allLogFilePath.toString() + tranFile.getOriginalFilename();
            FileUtils.writeByteArrayToFile(new File(tranPath), tranFile.getBytes());
            transName.add(tranPath);
        }
        //获取同目录下转换文件名
        String transNameStr = JSON.toJSONString(transName);
        kJobTrans.setJobTransPath(transNameStr);
        return kJobTrans;
    }

    /**
     * 修改保存新的作业跟作业关联的转换
     *
     * @param kJob
     * @param getuId
     * @param kettleFileRepository
     * @param jobFile
     * @param transFiles
     * @return
     * @throws IOException
     */
    public static KJobTrans saveNewJobFileAndTransFile(KJob kJob, Integer getuId, String kettleFileRepository, MultipartFile jobFile, MultipartFile[] transFiles) throws IOException {
        //如果之前的文件存在，删除目录
        if (FileUtil.exist(kJob.getJobPath())) {
            File orgFile = new File(kJob.getJobPath());
            FileUtil.del(orgFile.getParent());
        }
        return saveJobFileAndTransFile(getuId, kettleFileRepository, jobFile, transFiles);

    }

    /**
     * 重新上传作业的作业文件：
     * 1、job替换原先目录的job
     * 2、转换不变
     *
     * @param kJob
     * @param jobFile
     * @return
     */
    public static KJobTrans jobForSaveNewJobFile(KJob kJob, MultipartFile jobFile) throws IOException {
        //获取原先的jobpath，复制文件到原目录
        String orgJobPath = kJob.getJobPath();
        int lastPathFlag = orgJobPath.lastIndexOf("/");
        String orgJobParent = orgJobPath.substring(0, lastPathFlag + 1);
        File orgFileDir = new File(orgJobParent);
        if (!FileUtil.isNotEmpty(orgFileDir)) {
            //TODO 异常处理
            throw new IOException("原目录转换丢失");
        }
        //删除原文件
        if (FileUtil.exist(kJob.getJobPath())) {
            File orgJobFile = new File(orgJobPath);
            FileUtil.del(orgJobFile.getAbsoluteFile());
        }
        //新文件
        String jobPath = orgJobParent + jobFile.getOriginalFilename();
        //上传job到原目录
        FileUtils.writeByteArrayToFile(new File(jobPath), jobFile.getBytes());

        //定义返回
        KJobTrans kJobTrans = new KJobTrans();
        kJobTrans.setJobPath(jobPath);
        kJobTrans.setJobTransPath(kJob.getJobTransPath());
        return kJobTrans;
    }


    /**
     * 重新上传作业关联的转换：
     * 1、转换提交到最新目录
     * 2、复制最新的job到新目录， 删除原先目录
     *
     * @param kJob
     * @param getuId
     * @param kettleFileRepository
     * @param transFiles
     * @return
     */
    public static KJobTrans jobForSaveNewTransFiles(KJob kJob, Integer getuId, String kettleFileRepository, MultipartFile[] transFiles) throws IOException {
        //定义返回
        KJobTrans kJobTrans = new KJobTrans();
        List<String> transName = new ArrayList<>();
        //保存路径
        StringBuilder allLogFilePath = new StringBuilder();
        allLogFilePath.append(kettleFileRepository).append("/")
                .append(getuId).append("/")
                .append(System.currentTimeMillis()).append("/");
        //遍历保存转换
        for (MultipartFile tranFile : transFiles) {
            String tranPath = allLogFilePath.toString() + tranFile.getOriginalFilename();
            FileUtils.writeByteArrayToFile(new File(tranPath), tranFile.getBytes());
            transName.add(tranPath);
        }
        //获取同目录下转换文件名
        String transNameStr = JSON.toJSONString(transName);
        kJobTrans.setJobTransPath(transNameStr);

        //获取原先的jobpath，复制文件到新目录， 删除原先目录
        String orgJobPath = kJob.getJobPath();
        if (FileUtil.exist(kJob.getJobPath())) {
            File orgJobFile = new File(orgJobPath);
            String orgJobName = orgJobFile.getName();
            //新目录
            String newJobPath = allLogFilePath.toString() + orgJobName;
            //复制job
            FileUtil.copy(orgJobPath, newJobPath, true);
            //删除job原目录
            FileUtil.del(orgJobFile.getParent());
            kJobTrans.setJobPath(newJobPath);
            return kJobTrans;
        } else {
            //TODO 异常处理
            throw new IOException("原目录作业丢失");
        }
    }
}
